from django.contrib.auth.hashers import make_password
from django.db.models import Max
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import authenticate, login, logout
from django.views.decorators.csrf import csrf_protect

from bases.models import User, Student, Teacher, Administrator
from bases.models import Topic, Student
from .models import Progress
from .forms import ProgressForm
from django.contrib.auth.decorators import user_passes_test
from django.contrib import messages
from django.shortcuts import render, get_object_or_404
from django.core.exceptions import PermissionDenied
from django.utils import timezone
from notifications.models import Notification
def page_not_found(request, exception):
    return render(request, '404.html', status=404)
def get_or_create_teacher(user):
    try:
        return user.teacher_profile
    except Teacher.DoesNotExist:
        return Teacher.objects.create(
            user=user,
            teacher_id=f"T{user.id}",
            title="讲师",
            department="未分配"
        )

@csrf_protect
def login_view(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        role = request.POST.get('role')

        # 认证用户
        user = authenticate(request, username=username, password=password)

        if user and user.role == role:
            print(f"用户 {username} 登录成功")
            login(request, user)

            # 根据角色跳转
            if user.is_student:
                return redirect('student_dashboard')  # 学生界面
            elif user.is_teacher:
                return redirect('teacher_dashboard')  # 教师界面
            elif user.is_admin:
                return redirect('admin:index')        # 管理员后台
            else:
                return redirect('login')              # 默认回到登录页

        else:
            error = "登录失败，请检查用户名、密码或角色是否正确"
            return render(request, 'login.html', {'error': error})

    return render(request, 'login.html')


def logout_view(request):
    logout(request)  # 清除 session 和认证信息
    print("用户退出登录")
    return redirect('login')  # 跳转到登录页面
def base_view(request):
    return render(request, 'base.html')

def register(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        confirm_password = request.POST.get('confirm_password')
        email = request.POST.get('email')
        phone = request.POST.get('phone')
        role = request.POST.get('role')

        if password != confirm_password:
            return render(request, 'register.html', {'error': '两次输入的密码不一致'})

        if User.objects.filter(username=username).exists():
            return render(request, 'register.html', {'error': '用户名已存在'})
        max_id = User.objects.aggregate(max_id=Max('id'))['max_id'] or 0

        #暂时保留管理员创建
        user = User(
            id=max_id + 1,
            username=username,
            password=make_password(password),
            role=role,
            is_active=True,
            email=email,
            phone=phone
        )
        user.save()


        return redirect('login')
    return render(request, 'register.html')
def student_dashboard(request):
    return render(request, 'student/dashboard.html')

from bases.models import Student

def student_topics(request):
    if not request.user.is_student:
        raise PermissionDenied("您没有访问权限")

    try:
        # 显式获取 student_profile，如果不存在则创建
        student = request.user.student_profile
    except Student.DoesNotExist:
        # 自动创建一个 Student 实例
        student = Student.objects.create(
            user=request.user,
            student_id=f"temp_{request.user.id}",  # 临时学号
            major="未填写专业",
            grade=timezone.now().year,  # 当前年份作为年级
            class_name="未分配班级"
        )

    # 获取该学生的课题
    topics = Topic.objects.filter(student=request.user.student_profile)

    return render(request, 'student/topics.html', {'topics': topics})
def submit_question(request):
    if request.method == 'POST':
        # 处理提交问题的逻辑
        pass
    return render(request, 'student/submit_question.html')
def view_progress(request):
    return render(request, 'student/progress.html')


def submit_progress(request, topic_id):
    topic = get_object_or_404(Topic, id=topic_id)

    if request.method == 'POST':
        form = ProgressForm(request.POST, request.FILES)
        if form.is_valid():
            progress = form.save(commit=False)
            progress.topic = topic
            progress.student = request.user.student_profile
            progress.teacher = topic.teacher.user
            progress.save()
            messages.success(request, "进度提交成功！")
            return redirect('student_dashboard')
    else:
        form = ProgressForm()

    return render(request, 'student/submit_progress.html', {'form': form, 'topic': topic})

def evaluate_progress(request, progress_id):
    progress = Progress.objects.get(id=progress_id)

    if request.method == 'POST':
     score = request.POST.get('score')
    comment = request.POST.get('comment')
    status = request.POST.get('status')

    progress.score = score
    progress.comment = comment
    progress.status = status
    progress.save()

    messages.success(request, "评价已保存！")
    return redirect('teacher_dashboard')
def delete_progress(request, progress_id):
    progress = Progress.objects.get(id=progress_id)

    if progress.status is None:  # 未审核状态
        progress.delete()
        messages.success(request, "进度删除成功！")
    else:
        messages.warning(request, "该进度已被审核，无法删除。")

    return redirect('student_dashboard')
def delete_evaluation(request, progress_id):
    progress = Progress.objects.get(id=progress_id)

    if progress.status in ['passed', 'rejected']:
        progress.score = None
        progress.comment = ''
        progress.status = None
        progress.save()
        messages.success(request, "评分记录删除成功！")
    else:
        messages.warning(request, "该进度尚未被评分，无需删除。")

    return redirect('teacher_dashboard')
def edit_progress(request, progress_id):
    progress = Progress.objects.get(id=progress_id)

    if progress.status != 'rejected':  # 非驳回状态不允许修改
        messages.warning(request, "该进度未被驳回，无法修改。")
        return redirect('student_dashboard')

    if request.method == 'POST':
        form = ProgressForm(request.POST, request.FILES, instance=progress)
        if form.is_valid():
            form.save()
            messages.success(request, "进度修改成功！")
            return redirect('student_dashboard')
    else:
        form = ProgressForm(instance=progress)

    return render(request, 'student/edit_progress.html', {'form': form, 'progress': progress})
def adjust_evaluation(request, progress_id):
    progress = Progress.objects.get(id=progress_id)

    if request.method == 'POST':
        score = request.POST.get('score')
        comment = request.POST.get('comment')

        progress.score = score
        progress.comment = comment
        progress.save()

        messages.success(request, "评分调整成功！")
        return redirect('teacher_dashboard')

    return render(request, 'teacher/adjust_evaluation.html', {'progress': progress})
def view_progress(request, topic_id):
    topic = Topic.objects.get(id=topic_id)
    progresses = Progress.objects.filter(topic=topic).order_by('submitted_at')

    return render(request, 'student/view_progress.html', {'topic': topic, 'progresses': progresses})
def progress_statistics(request):
    # 示例：按学生统计
    students = Student.objects.all()
    student_stats = []

    for student in students:
        topics = Topic.objects.filter(student=student)
        total_stages = len(topics) * 3  # 每个课题有三个阶段
        completed_stages = Progress.objects.filter(topic__in=topics, status='passed').count()
        completion_rate = (completed_stages / total_stages) * 100 if total_stages > 0 else 0

        student_stats.append({
            'student': student,
            'completion_rate': f"{completion_rate:.2f}%"
        })

    return render(request, 'teacher/progress_statistics.html', {'student_stats': student_stats})
def list_topics(request):
    if not request.user.is_student:
        raise PermissionDenied("您没有访问权限")

    # 获取所有可用的课题（status='available' 且 student 为空）
    available_topics = Topic.objects.filter(status='available', student__isnull=True)

    # 获取该学生已申请的课题
    applied_topics = Topic.objects.filter(student=request.user.student_profile)

    return render(request, 'student/list_topics.html', {
        'topics': available_topics,
        'applied_topics': applied_topics
    })
def apply_topic(request, topic_id):
    topic = get_object_or_404(Topic, id=topic_id)

    if topic.student is not None:
        messages.warning(request, "该课题已被其他学生申请")
        return redirect('list_topics')

    topic.student = request.user.student_profile
    topic.status = 'pending'
    topic.save()

    messages.success(request, "课题申请成功，请等待教师审核")
    return redirect('list_topics')
def teacher_dashboard(request):
    if not request.user.is_teacher:
        raise PermissionDenied("您没有访问权限")

    teacher = get_or_create_teacher(request.user)

    topics = Topic.objects.filter(teacher=teacher)
    students = Student.objects.filter(topic__in=topics).distinct()
    pending_topics = Topic.objects.filter(teacher=teacher, status='pending')

    return render(request, 'teacher/dashboard.html', {
        'students': students,
        'topics': topics,
        'pending_topics': pending_topics
    })

def evaluate_progress_list(request):
    if not request.user.is_teacher:
        raise PermissionDenied("您没有访问权限")

    teacher = get_or_create_teacher(request.user)

    topics = Topic.objects.filter(teacher=teacher)
    progresses = Progress.objects.filter(topic__in=topics)

    return render(request, 'teacher/progress_list.html', {
        'progresses': progresses
    })

def topic_review(request):
    if not request.user.is_teacher:
        raise PermissionDenied("您没有访问权限")

    teacher = get_or_create_teacher(request.user)

    topics = Topic.objects.filter(teacher=teacher, status='pending')

    if request.method == 'POST':
        action = request.POST.get('action')
        topic_id = request.POST.get('topic_id')
        topic = get_object_or_404(Topic, id=topic_id, teacher=teacher)

        if action == 'approve':
            topic.status = 'approved'
            messages.success(request, f"课题 '{topic.name}' 已批准")
        elif action == 'reject':
            topic.status = 'rejected'
            messages.warning(request, f"课题 '{topic.name}' 已驳回")

        topic.save()

    return render(request, 'teacher/topic_review.html', {
        'topics': topics
    })

def my_students(request):
    if not request.user.is_teacher:
        raise PermissionDenied("您没有访问权限")

    teacher = get_or_create_teacher(request.user)

    topics = Topic.objects.filter(teacher=teacher)
    students = Student.objects.filter(topic__in=topics).distinct()

    return render(request, 'teacher/my_students.html', {
        'students': students
    })
def student_dashboard(request):
    # 判断是否有未读通知
    has_unread_notifications = False
    if request.user.is_authenticated:
        has_unread_notifications = request.user.notifications.filter(is_read=False).exists()

    return render(request, 'student/dashboard.html', {
        'has_unread_notifications': has_unread_notifications,
    })

